package com.micai.boss.weixin.repository;

import com.alibaba.fastjson.JSON;
import com.micai.boss.base.constant.ErrorCodeEnum;
import com.micai.boss.base.exception.ServiceException;
import com.micai.boss.base.utils.AssertUtils;
import com.micai.boss.weixin.constant.WeiXinConstant;
import com.micai.boss.weixin.entity.AccessToken;
import com.micai.boss.weixin.service.dto.WeixinUserInfoDto;
import com.micai.boss.weixin.util.WeixinUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

/**
 * 描述：微信用户
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/4/19 17:35
 */
@Repository
public class WeiXinUserRepository extends AbstractWeiXinRepository {

    private Logger logger = LoggerFactory.getLogger(WeiXinUserRepository.class);

    private static final String wxuserInfoUrl = "https://api.weixin.qq.com/cgi-bin/user/info";

    @Override
    protected String getRedisKey() {
        return "WEIXIN_USER_KEY";
    }

    /**
     * 获取用户信息
     * @param openId
     * @return
     */
    public WeixinUserInfoDto getUserInfo(String openId){
        /*https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
        https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN*/
        String cache_userInfo = (String) super.get(WeiXinConstant.WX_CACHE_USER_INFO_KEY + openId);
        if(!StringUtils.isEmpty(cache_userInfo)){
            return JSON.parseObject(cache_userInfo,WeixinUserInfoDto.class);
        }
        AccessToken accessToken = this.getAccessToken();
        if(null == accessToken){
            throw new ServiceException(ErrorCodeEnum.系统异常.getCode(),"获取token异常");
        }
        String access_token = accessToken.getToken();
        AssertUtils.notNull(access_token,ErrorCodeEnum.参数为空.getMessage());
        AssertUtils.notNull(openId,ErrorCodeEnum.参数为空.getMessage());
        StringBuffer userInfoUrl = new StringBuffer();
        /*userInfoUrl.append("https://api.weixin.qq.com/cgi-bin/user/info?access_token=");*/
        userInfoUrl.append(wxuserInfoUrl + "?access_token=");
        userInfoUrl.append(access_token);
        userInfoUrl.append("&openid=");
        userInfoUrl.append(openId);
        userInfoUrl.append("&lang=zh_CN");
        String url = userInfoUrl.toString();
        logger.info("getUserInfo requstUrl:{}",url);
        String response = WeixinUtil.httpsRequestWithStringReturn(url,"GET",null);
        logger.info("getUserInfo response:{}",response);
        if(StringUtils.isEmpty(response)){
            throw new ServiceException(ErrorCodeEnum.系统异常.getCode(),"获取用户信息失败");
        }
        super.put(WeiXinConstant.WX_CACHE_USER_INFO_KEY + openId,response,60 * 24 * 30);
        WeixinUserInfoDto weixinUserInfoDto = JSON.parseObject(response,WeixinUserInfoDto.class);
        try {
            if (null != weixinUserInfoDto && !StringUtils.isEmpty(weixinUserInfoDto.getUnionid())) {
                /*BaseResult<Boolean> baseResult = userService.recordUnionIdByopenId(openId, weixinUserInfoDto.getUnionid());
                logger.info("调用用户服务recordUnionIdByopenId返回结果:{}", JSON.toJSONString(baseResult));*/
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return weixinUserInfoDto;
    }

}
